package cn.edu.zjut.mina.protocal;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;


/** 
 * JMessageProtocal编码 
 * @author Simple 
 * 
 */  
public class JMessageProtocalEncoder extends ProtocolEncoderAdapter {  
  
  private Charset charset;  
  
  public JMessageProtocalEncoder(Charset charset) {  
    this.charset=charset;  
  }  
  
  /** 
   * 编码 
   */  
  public void encode(IoSession session, Object object, ProtocolEncoderOutput out) throws Exception {  
    // new buf  
    IoBuffer buf=IoBuffer.allocate(2048).setAutoExpand(true);  
    // object --> AbsMP  
    JAbsMessageProtocal absMp=(JAbsMessageProtocal)object;  
    buf.put(absMp.getTag());  
    buf.putInt(absMp.getLength());  
    if(object instanceof JMessageProtocalReq) {// 请求协议  
      JMessageProtocalReq mpReq=(JMessageProtocalReq)object;  
      buf.putShort(mpReq.getFunctionCode());  
      buf.putString(mpReq.getContent(), charset.newEncoder());  
    } else if(object instanceof JMessageProtocalRes) {// 响应协议  
      JMessageProtocalRes mpRes=(JMessageProtocalRes)object;  
      buf.put(mpRes.getResultCode());  
      buf.putString(mpRes.getContent(), charset.newEncoder());  
    }  
    buf.flip();  
    out.write(buf);  
  }  
}  
